package com.zhongpengcheng.adapter.impl;

import com.alibaba.fastjson.JSON;
import com.zhongpengcheng.adapter.RedisAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis适配器
 * @author ZhongPengCheng
 * @version 1.0
 * @since 2021-12-04 16:17:00
 */
@Slf4j
@Component
public class RedisAdapterImpl implements RedisAdapter {
    @Autowired
    private StringRedisTemplate strRedis;

    @Override
    public void setWithExpire(String key, String value, long timeout, TimeUnit timeUnit) {
        strRedis.opsForValue().set(key, value, timeout, timeUnit);
    }

    @Override
    public String get(String key) {
        return strRedis.opsForValue().get(key);
    }

    @Override
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(strRedis.hasKey(key));
    }

    @Override
    public void setWithExpire(String key, Object value, long timeout, TimeUnit timeUnit) {
        setWithExpire(key, JSON.toJSONString(value), timeout, timeUnit);
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {
        String value = get(key);
        try {
            return JSON.parseObject(value, clazz);
        } catch (Exception e) {
            log.error("redis数据解析失败, value={}, class={}", value, clazz);
        }
        return null;
    }
}
